import pandas as pd
with open('金庸-射雕英雄传txt精校版.txt','r',encoding='GBK') as f:
    txt = f.readlines()
number_dict = {
    '一':1,'二':2,'三':3,'四':4,'五':5,'六':6,'七':7,'八':8,'九':9,'十':10,
}
def str2int(chap):
    if len(chap) == 1:
        return number_dict[chap]
    elif len(chap) == 2:
        if chap[0] == '十':
            return 10 + number_dict[chap[1]]
        elif chap[1] == '十':
            return number_dict[chap[0]]*10
        print('Error')
    elif len(chap) == 3:
        return number_dict[chap[0]]*10 + number_dict[chap[2]]
    print('Error')


def cut_sentences(content):
    end_flag = ['?', '!', '.', '？', '！', '。', '…', '”']
    content_len = len(content)
    sentences = []
    tmp_char = ''
    for idx, char in enumerate(content):
        tmp_char += char
        if (idx + 1) == content_len:
            sentences.append(tmp_char)
            break
        # 判断此字符是否为结束符号
        if char in end_flag:
            # 再判断下一个字符是否为结束符号，如果不是结束符号，则切分句子
            next_idx = idx + 1
            if not content[next_idx] in end_flag:
                sentences.append(tmp_char)
                tmp_char = ''

    return sentences
paradix = 0
chap = 0
res = []
for line in txt:
    line = line.strip()
    if not line:
        continue
    if '全书完' in line:
        break
    if line.startswith('第'):
        chapter = line.split(' ')
        if chapter[0].endswith('回'):
            chap = str2int(chapter[0][1:-1])
            paradix = 0
    if chap == 0:
        continue
    for sentence in cut_sentences(line):
        res.append((sentence, paradix, chap))
    paradix += 1
raw = pd.DataFrame(res, columns=['txt', 'paradix', 'chap'])
tmpchap = raw[raw['chap'] == 7].copy()
tmpchap.reset_index(drop=True,inplace=True)
print(tmpchap.head(20))

